package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.excel.StudentGradeExcel;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 临时学员，补课学员 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-11-06
 */
@RestController
@RequestMapping("/api/studentGradeTemporary")
public class StudentGradeTemporaryController extends BaseController {
    @Autowired
    IStudentGradeTemporaryService studentGradeTemporaryService;

    @Autowired
    ICourseService courseService;

    @Autowired
    ICourseSchedulingDetailService courseSchedulingDetailService;

    @Autowired
    IGradeService gradeService;

    @Autowired
    IRecordCourseService recordCourseService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IStudentService iStudentService;

    /**
     * 获取临时学员
     *
     * @param startDate   开始日期
     * @param endDate     结束日期
     * @param yearPart    年份
     * @param quarterNum  学期
     * @param schoolId    校区
     * @param subjectsId  科目
     * @param courseId    课程id
     * @param lessonType  课程类型，1精品课，2智能课，3刷题班
     * @param teacherId   老师id
     * @param gradeName   班级名称
     * @param studentName 学生姓名
     * @param isExport    是否为导出，1是，0否
     */
    @GetMapping("")
    public Result getAll(@RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
                         @RequestParam(value = "pageSize", defaultValue = "-1") Integer pageSize,
                         @RequestParam(value = "startDate", required = false) String startDate,
                         @RequestParam(value = "endDate", required = false) String endDate,
                         @RequestParam(value = "yearPart", required = false) String yearPart,
                         @RequestParam(value = "quarterNum", required = false) String quarterNum,
                         @RequestParam(value = "schoolId", required = false) String schoolId,
                         @RequestParam(value = "subjectsId", required = false) String subjectsId,
                         @RequestParam(value = "courseId", required = false) String courseId,
                         @RequestParam(value = "lessonType", required = false) String lessonType,
                         @RequestParam(value = "teacherId", required = false) String teacherId,
                         @RequestParam(value = "gradeName", required = false) String gradeName,
                         @RequestParam(value = "studentName", required = false) String studentName,
                         @RequestParam(value = "isExport", defaultValue = "0", required = false) String isExport) throws IOException {

        IPage<StudentGradeTemporary> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(schoolId), "t2.school_id", schoolId);
        wrapper.eq(StringUtils.isNotBlank(subjectsId), "t2.subjects_id", subjectsId);
        wrapper.eq(StringUtils.isNotBlank(courseId), "t3.id", courseId);
        wrapper.eq(StringUtils.isNotBlank(lessonType), "t1.lesson_type", lessonType);
        wrapper.eq(StringUtils.isNotBlank(teacherId), "t2.teacher_id", teacherId);
        wrapper.like(StringUtils.isNotBlank(gradeName), "t2.`name`", gradeName);
        wrapper.like(StringUtils.isNotBlank(studentName), "t4.`name`", studentName);
        wrapper.eq(StringUtils.isNotBlank(yearPart), "t1.year_part", yearPart);
        wrapper.eq(StringUtils.isNotBlank(quarterNum), "t1.quarter_num", quarterNum);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            wrapper.between("t1.school_date", startDate, endDate);
        }
        wrapper.eq("t1.deleted", 0);
        wrapper.orderByDesc("t1.id");

        studentGradeTemporaryService.selectStudentGradeTemporaryPage(iPage, wrapper);

        if (isExport.equals("1")) {

            List<String> headList = new ArrayList<>();
            headList.add("学生姓名");
            headList.add("上课日期");
            headList.add("上课时段");
            headList.add("校区");
            headList.add("班级");
            headList.add("所属课程");
            headList.add("科目");
            headList.add("课程类型");
            headList.add("带班教师");
            headList.add("上课类型");
            headList.add("是否过期");

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("临时学员");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setFontHeightInPoints((short) 11);
            headerCellStyle.setFont(headerFont);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Row headerRow = sheet.createRow(0);
            sheet.createFreezePane(0, 1);// 冻结首行

            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }

            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFont(headerFont);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            int rowNum = 1;
            for (StudentGradeTemporary temporary : iPage.getRecords()) {
                Row row = sheet.createRow(rowNum++);

                Cell cell = row.createCell(0);
                cell.setCellValue(temporary.getStudentName());
                sheet.setColumnWidth(0, 20 * 256);
                cell.setCellStyle(cellStyle);

                Cell cell1 = row.createCell(1);
                cell1.setCellValue(temporary.getSchoolDate().toString());
                sheet.setColumnWidth(1, 25 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(2);
                cell2.setCellValue(temporary.getTimeStart() + " - " + temporary.getTimeEnd());
                sheet.setColumnWidth(2, 25 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(3);
                cell3.setCellValue(temporary.getSchoolName());
                sheet.setColumnWidth(3, 20 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(4);
                cell4.setCellValue(temporary.getGradeName());
                sheet.setColumnWidth(4, 35 * 256);
                cell4.setCellStyle(cellStyle);

                Cell cell5 = row.createCell(5);
                cell5.setCellValue(temporary.getCourseName());
                sheet.setColumnWidth(5, 35 * 256);
                cell5.setCellStyle(cellStyle);

                Cell cell6 = row.createCell(6);
                if (temporary.getSubjectsId() != null) {
                    cell6.setCellValue(CommonUtil.getSubjectsNameForId(Math.toIntExact(temporary.getSubjectsId())));
                }
                sheet.setColumnWidth(6, 15 * 256);
                cell6.setCellStyle(cellStyle);

                Cell cell7 = row.createCell(7);
                if (temporary.getLessonType() != null) {
                    cell7.setCellValue(CommonUtil.getLessonTypeName(temporary.getLessonType()));
                }
                sheet.setColumnWidth(7, 20 * 256);
                cell7.setCellStyle(cellStyle);

                Cell cell8 = row.createCell(8);
                cell8.setCellValue(temporary.getTeacherName());
                sheet.setColumnWidth(8, 20 * 256);
                cell8.setCellStyle(cellStyle);

                Cell cell9 = row.createCell(9);
                if (temporary.getType() != null) {
                    if (temporary.getType() == 0) {
                        cell9.setCellValue("临时");
                    } else if (temporary.getType() == 1) {
                        cell9.setCellValue("补课");
                    }
                }
                sheet.setColumnWidth(9, 20 * 256);
                cell9.setCellStyle(cellStyle);

                Cell cell10 = row.createCell(10);

                if (temporary.getStartDateTime().isBefore(LocalDateTime.now())) {
                    cell10.setCellValue("是");
                } else {
                    cell10.setCellValue("否");
                }

                sheet.setColumnWidth(10, 15 * 256);
                cell10.setCellStyle(cellStyle);

            }

            String fileName = "临时学员表" + ".xls";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
        }

        return new

                Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.

                getTotal(), iPage.

                getPages()), Code.GET_OK_MSG);
    }

    /**
     * 添加日程
     */
    @PostMapping()
    public Result save(@RequestBody StudentGradeTemporary studentGradeTemporary) {
        Grade grade = iGradeService.getById(studentGradeTemporary.getGradeId());

        for (Long studentId : studentGradeTemporary.getStudentIdList()) {
            for (LocalDate schoolDate : studentGradeTemporary.getSchoolDateList()) {
                StudentGradeTemporary temporary = new StudentGradeTemporary();
                temporary.setGradeId(studentGradeTemporary.getGradeId());
                temporary.setStudentId(studentId);
                temporary.setType(studentGradeTemporary.getType());
                temporary.setSchoolDate(schoolDate);

                CourseSchedulingDetail schedulingDetail = courseSchedulingDetailService.getOne(new QueryWrapper<CourseSchedulingDetail>()
                        .eq("grade_id", studentGradeTemporary.getGradeId())
                        .eq("school_date", schoolDate)
                        .last("limit 1"));

                // 判断该日期是否已经被保存过，如果已经被保存过，则不能重复添加
                QueryWrapper<StudentGradeTemporary> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("student_id", studentId);
                queryWrapper.eq("school_date", schoolDate);
                queryWrapper.eq("grade_id", studentGradeTemporary.getGradeId());
                queryWrapper.eq("type", studentGradeTemporary.getType());
                long count = studentGradeTemporaryService.count(queryWrapper);
                if (count > 0) {
                    return new Result(Code.ERROR, null, "【" + iStudentService.getById(studentId).getName() + "】" + schoolDate.toString() + " 该日期已添加过，请勿重复添加");
                }

                temporary.setYearPart(schedulingDetail.getYearPart());
                temporary.setQuarterNum(schedulingDetail.getQuarter());
                temporary.setTimeStart(schedulingDetail.getTimeStart());
                temporary.setTimeEnd(schedulingDetail.getTimeEnd());
                temporary.setStartDateTime(schedulingDetail.getStartDateTime());
                temporary.setEndDateTime(schedulingDetail.getEndDateTime());
                temporary.setLessonType(grade.getLessonType());
                temporary.setSubjectsId(schedulingDetail.getSubjectsId());
                temporary.setYearClassId(grade.getYearClassId().getKey());

                studentGradeTemporaryService.save(temporary);
            }
        }

        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }

    /**
     * 删除日程
     */
    @DeleteMapping("")
    public Result delete(@RequestParam(value = "ids") String ids) {
        if (StringUtils.isBlank(ids)) {
            return new Result(Code.ERROR, null, "参数不能为空");
        }
        String[] idStr = ids.split(",");
        for (String id : idStr) {
            StudentGradeTemporary studentGradeTemporary = studentGradeTemporaryService.getById(id);
            if (Objects.isNull(studentGradeTemporary)) {
                return new Result(Code.EXP_ERROR, null, "该日程不存在");
            }

            // 判断该日程是否已经被使用，如果已经被使用，则不能删除
            Long count = recordCourseService.count(new QueryWrapper<RecordCourse>()
                    .eq("student_id", studentGradeTemporary.getStudentId())
                    .eq("course_type", 7)
                    .eq("type", 2)
                    .eq("`status`", 1)
                    .eq("school_date", studentGradeTemporary.getSchoolDate())
                    .eq("grade_id", studentGradeTemporary.getGradeId()));

            if (count > 0) {
                return new Result(Code.ERROR, null, studentGradeTemporary.getSchoolDate() + " 该日程已上课，不能删除");
            }

            studentGradeTemporaryService.removeById(Long.parseLong(id));
        }

        return new Result(Code.DELETE_OK, null, Code.DELETE_OK_MSG);
    }

    /**
     * 获取学生列表
     */
    @GetMapping("/getStudentList")
    public Result getStudentList(@RequestParam(value = "pageNum", defaultValue = "-1") Integer pageNum,
                                 @RequestParam(value = "pageSize", defaultValue = "-1") Integer pageSize,
                                 @RequestParam(value = "startDate", required = false) String startDate,
                                 @RequestParam(value = "endDate", required = false) String endDate,
                                 @RequestParam(value = "gradeId", required = false) String gradeId,
                                 @RequestParam(value = "studentName", required = false) String studentName) {

        IPage<Student> iPage = new Page<>(pageNum, pageSize);

        if (StringUtils.isBlank(gradeId)) {
            return new Result(Code.ERROR, null, "请先选择班级");
        }

        Grade grade = iGradeService.getById(gradeId);

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(studentName), "b.`name`", studentName);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            queryWrapper.between("a.handle_date", startDate, endDate);
        }
        queryWrapper.ne("a.`status`", 2);
        queryWrapper.gt("a.residue_course_count ", 0);
        queryWrapper.eq("a.deleted", 0);
        queryWrapper.eq("a.lesson_type", grade.getLessonType());
        queryWrapper.eq("a.subjects_id", grade.getSubjectsId());
        queryWrapper.eq("a.year_class_id", grade.getYearClassId());
        queryWrapper.eq("a.school_id", grade.getSchoolId());
        queryWrapper.groupBy("a.student_id");

        studentGradeTemporaryService.selectStudentList(iPage, queryWrapper);

        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 获取可选排课日期
     */
    @GetMapping("/getAvailableDates")
    public Result getAvailableDates(@RequestParam(value = "gradeId", required = false) String gradeId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        queryWrapper.eq("status", 0);
        queryWrapper.ge("start_date_time", LocalDate.now());

        List<CourseSchedulingDetail> courseSchedulingDetailList = courseSchedulingDetailService.list(queryWrapper);

        return new Result(Code.OK, courseSchedulingDetailList, Code.GET_OK_MSG);
    }

    /**
     * 获取可选班级
     */
    @GetMapping("/getGradeList")
    public Result getGradeList(@RequestParam(value = "schoolId", required = false) String schoolId,
                               @RequestParam(value = "subjectId", required = false) String subjectId,
                               @RequestParam(value = "lessonType", required = false) String lessonType) {

        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(schoolId)) {
            queryWrapper.inSql("t1.school_id", schoolId);
        } else {
            queryWrapper.in("t1.school_id", this.baseSchoolIdList);
        }
        queryWrapper.eq(StringUtils.isNotBlank(subjectId), "t1.subjects_id", subjectId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType), "t1.lesson_type", lessonType);
        queryWrapper.eq("t1.deleted", 0);
        queryWrapper.eq("t1.`status`", 1);
        queryWrapper.groupBy("t1.id");
        queryWrapper.having("( t1.full_count = 0 OR ( t1.full_count > student_count ))");

        List<Grade> selectGradeList = studentGradeTemporaryService.selectGradeList(queryWrapper);

        return new Result(Code.OK, selectGradeList, Code.GET_OK_MSG);
    }


}
